package com.aliyun.flashsale.portal.web;

import java.util.Date;

import com.aliyun.commons.model.Result;
import com.aliyun.flashsale.client.model.FlashSaleProductDTO;
import com.aliyun.flashsale.client.service.FlashSaleProductService;
import com.aliyun.flashsale.portal.config.AppConfig;
import com.aliyun.flashsale.portal.model.ApiResult;
import com.aliyun.flashsale.portal.model.ProductInfoDTO;
import com.aliyun.flashsale.portal.service.CreateOrderService;
import com.aliyun.flashsale.portal.service.ProductQueryService;
import com.aliyun.inventory.client.service.InventoryService;
import com.aliyun.order.client.model.OrderDetailDTO;
import com.aliyun.order.client.model.OrderDetailDTO.OrderItemDTO;
import com.aliyun.order.client.service.OrderService;
import com.aliyun.product.client.model.ProductDTO;
import com.aliyun.product.client.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 控制器
 *
 * 
 * @date 2024/11/27
 */
@Controller
public class MainController {

    private static final String REDIRECT_PRODUCT_FORMAT = "redirect:/product/%d.htm";

    @Autowired
    private ProductQueryService productQueryService;
    @Autowired
    private CreateOrderService createOrderService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private ProductService productService;
    @Autowired
    private InventoryService inventoryService;
    @Autowired
    private AppConfig appConfig;
    @Autowired
    private FlashSaleProductService flashSaleProductService;

    /**
     * 商品管理页
     *
     * @return {@link String }
     */
    @GetMapping("/")
    public String index() {
        return getProductURL();
    }

    /**
     * 商品详情页
     *
     * @param productId 商品 ID
     * @param model     模型
     * @return {@link String }
     */
    @GetMapping("/product/{productId}.htm")
    public String productDetail(@PathVariable long productId, Model model) {
        Long defaultProductId = appConfig.getDefaultFlashSaleProductId();
        if (productId != defaultProductId) {
            return getProductURL();
        }
        ProductInfoDTO productInfo = productQueryService.getProductInfo(productId);
        model.addAttribute("productInfo", productInfo);
        return "product_detail";
    }

    /**
     * 获取商品信息
     *
     * @param userId 用户 ID
     * @return {@link String }
     */
    @GetMapping("/product-info")
    @ResponseBody
    public ApiResult<ProductInfoDTO> getProductInfo(@RequestParam(defaultValue = "0") long userId) {
        if (userId <= 0) {
            userId = appConfig.getDefaultUserId();
        }
        Long defaultProductId = appConfig.getDefaultFlashSaleProductId();
        ProductInfoDTO productInfo = productQueryService.getProductAndUserPurchaseInfo(defaultProductId, userId);
        return ApiResult.success(buildProductDTO(productInfo));
    }

    /**
     * 订单详情页
     *
     * @param orderId 订单 ID
     * @param model   型
     * @return {@link String }
     */
    @GetMapping("/order_detail.htm")
    public String orderDetail(long orderId, Model model) {
        Result<OrderDetailDTO> getOrderDetailResult = orderService.getOrderDetail(orderId);
        if (!getOrderDetailResult.isSuccess() || getOrderDetailResult.getData() == null) {
            throw new RuntimeException("invalid orderId");
        }
        model.addAttribute("orderInfo", getOrderDetailResult.getData());
        // 当前一个订单只有一个商品，所以直接取第一个即可
        Long productId = getOrderDetailResult.getData().getOrderItemDTOList().stream().map(OrderItemDTO::getProductId)
            .findFirst().get();
        Result<ProductDTO> productDTOResult = productService.getProduct(productId);
        if (!productDTOResult.isSuccess() || productDTOResult.getData() == null) {
            throw new RuntimeException("invalid productId");
        }
        model.addAttribute("productInfo", productDTOResult.getData());
        return "order_detail";
    }

    /**
     * 创建订单
     *
     * @param productId 商品 ID
     * @param userId    用户 ID
     * @param quantity  数量
     * @return {@link ApiResult }<{@link String }>
     */
    @PostMapping("/create-order")
    @ResponseBody
    public ApiResult<Long> createOrder(long productId, @RequestParam(defaultValue = "0") long userId,
        @RequestParam(defaultValue = "1") int quantity) {
        Long defaultProductId = appConfig.getDefaultFlashSaleProductId();
        if (productId != defaultProductId) {
            throw new RuntimeException("invalid productId");
        }
        if (userId <= 0) {
            userId = appConfig.getDefaultUserId();
        }
        if (quantity <= 0) {
            quantity = appConfig.getDefaultUserPurchaseQuantity();
        }
        long orderId = createOrderService.createOrder(userId, productId, quantity);
        return ApiResult.success(orderId);
    }

    /**
     * 重置缓存
     *
     * @return {@link String }
     */
    @GetMapping("/clear-cache")
    @ResponseBody
    public String resetCache() {
        Long defaultProductId = appConfig.getDefaultFlashSaleProductId();
        Long defaultUserId = appConfig.getDefaultUserId();
        flashSaleProductService.resetCache(defaultProductId);
        Result<FlashSaleProductDTO> flashSaleProduct = flashSaleProductService.getFlashSaleProduct(defaultProductId);
        Long productId = flashSaleProduct.getData().getProductId();
        productService.resetCache(productId);
        inventoryService.resetCache(productId, defaultUserId);
        return "缓存重置成功!";
    }

    /**
     * 构建商品 DTO
     *
     * @param productInfo 商品信息
     * @return {@link ProductInfoDTO }
     */
    private ProductInfoDTO buildProductDTO(ProductInfoDTO productInfo) {
        ProductInfoDTO productInfoDTO = new ProductInfoDTO();
        productInfoDTO.setProductId(productInfo.getProductId());
        productInfoDTO.setOriginalPrice(productInfo.getOriginalPrice());
        productInfoDTO.setFlashSalePrice(productInfo.getFlashSalePrice());
        productInfoDTO.setStatus(productInfo.getStatus());
        productInfoDTO.setStartTime(productInfo.getStartTime());
        productInfoDTO.setEndTime(productInfo.getEndTime());
        productInfoDTO.setTotalQuantity(productInfo.getTotalQuantity());
        productInfoDTO.setRemainQuantity(productInfo.getRemainQuantity());
        productInfoDTO.setServerTime(new Date());
        productInfoDTO.setMaxPurchasePerUser(productInfo.getMaxPurchasePerUser());
        productInfoDTO.setUserPurchased(productInfo.getUserPurchased());
        return productInfoDTO;
    }

    /**
     * 获取商品网址
     *
     * @return {@link String }
     */
    private String getProductURL() {
        return String.format(REDIRECT_PRODUCT_FORMAT, appConfig.getDefaultFlashSaleProductId());
    }
}
